from langgraph.config import get_stream_writer
from langchain_core.runnables import RunnableConfig

from app.graph.BaseNode import BaseNode
from app.graph.state import State


class NodeChatbot(BaseNode):
    def __call__(self, state: State, config: RunnableConfig):
        tid = self.get_tid(config)

        messages = self.get_latest_human_messages(tid, 1)
        if len(messages) == 0:
            raise RuntimeError("没有用户回复")  # TODO: 测试抛出异常会怎样
        message = messages[-1]

        writer = get_stream_writer()
        tokens = self.deepseek_r1([{"role": "user", "content": message.content}])
        for token in tokens:
            writer(token)

        return {}
